<template>
  <!--图片上传-->
  <div class="upload-img-wrap">
    <el-upload
      ref="fileupload"
      :on-preview="handlePictureCardPreview"
      class="upload-img"
      action="#"
      list-type="picture-card"
      :http-request="uploadFile"
      :before-upload="beforeUploadFile"
      :on-success="onUploadFileSuccess"
      :on-error="onUplodeFileError"
      :before-remove="handleBeforeRemove"
      :on-remove="handleRemove"
      :on-change="handleChange"
      multiple
      :file-list="fileList"
      :limit="5"
      :on-exceed="handleExceed"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :modal="false" :visible.sync="dialogVisible">
      <img class="img" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
// 图片上传/下载
import { fileUpload, imgDownLoad } from '@/api/common/upload.js'
export default {
  name: 'ImageUpload',
  props: {
    // 上传的附件回显
    editFileList: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      fileIdsList: [], // 用于存储附件的数组(只存id)
      fileList: [], // 存放编辑 文件的集合（附件回显）
      newFileList: [], // 返回父组件对象数据
      dialogImageUrl: '', // 点击放大的图片
      dialogVisible: false, // 点击放大的图片弹层
      deleteFileIds: [] // 删除的文件id
    }
  },
  computed: {
  },
  watch: {
    editFileList(val) {
      if (val !== undefined && val.length > 0) {
        this.newFileList = val
        this.fileIdsList = val.map(item => { return item.fileId })
        for (const i in this.fileIdsList) {
          this.imgDownLoad(this.fileIdsList[i])
        }
      } else {
        this.fileList = []
        this.fileIdsList = []
        this.newFileList = []
      }
    },
    fileIdsList(val) {
      if (val !== undefined && val.length > 0) {
        this.changeFileIdsList()
      }
    }
  },
  mounted() {
  },
  methods: {
    // 附件上传之前调用的函数，控制附件上传的大小和格式
    beforeUploadFile(file) {
      const isLt30M = file.size / 1024 / 1024 < 30
      if (!isLt30M) {
        this.msgError('上传文件大小不能超过 30MB!')
        return false
      }
      return true
    },
    // 自定义文件上传
    uploadFile(e) {
      const formData = new FormData()
      formData.append('file', e.file)
      fileUpload(formData).then(res => {
        e.onSuccess(res)
      }).catch((err) => {
        e.onError(err)
      })
    },
    // 上传的文件改变时调用的方法，附件新增 附件删除都会调用
    handleChange(file, fileList) {
      this.fileList = fileList
    },
    // 上传文件成功的回调
    onUploadFileSuccess(res, file) {
      if (res) {
        const fileData = res.data.fileId
        this.newFileList.push(res.data)
        this.fileIdsList.push(fileData) // 填充上传文件列表
        this.msgSuccess('上传成功')
      } else {
        this.msgError(res.message)
      }
    },
    // 限制文件上传的个数
    handleExceed(files, fileList) {
      this.msgWarning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    // 图片上传失败的回调
    onUplodeFileError(err, file, fileList) {
      if (err.message === 'Network Error') {
        this.msgError('上传文件过大或者磁盘已满')
      } else {
        this.msgError('上传文件过大或者磁盘已满')
      }
    },
    // 文件删除之前操作
    handleBeforeRemove(file, fileList) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 在这里真正的处理文件列表
        this.handleRemove(file, fileList)
      }).catch(() => {
        this.msgWarning('已取消删除')
      })
      return false // 这是重点,不管上面的操作结果如何都返回false
    },
    // 文件删除
    handleRemove(file, fileList) {
      // eslint-disable-next-line no-prototype-builtins
      const isRe = file.hasOwnProperty('response')
      let fileId = null
      if (isRe) {
        fileId = file.response.data.fileId
      } else {
        fileId = file.fileId
      }
      if (fileId) {
        this.deleteFileIds.push(fileId)
        this.fileIdsList.splice(this.fileIdsList.findIndex(item => item === fileId), 1)
        this.fileList.splice(this.fileList.findIndex(item => item.fileId === fileId), 1)
        this.newFileList.splice(this.newFileList.findIndex(item => item.fileId === fileId), 1)
      }
    },
    // 把上传的附件信息回传给父组件
    changeFileIdsList() {
      const fileIdsList = this.fileIdsList
      const deleteFileIds = this.deleteFileIds
      const newFileList = this.newFileList
      this.$emit('getFileIdsList', fileIdsList, deleteFileIds, newFileList)
    },
    // 预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 图片回显
    imgDownLoad(id) {
      this.fileList = []
      const data = { id: id }
      imgDownLoad(data).then(res => {
        // 将从后台获取的图片流进行转换
        this.url = 'data:image/png;base64,' + btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))
        const item = { url: this.url, fileId: id }
        this.fileList.push(item)
      })
    }
  }
}
</script>

<style lang="scss">
  .upload-img {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      color: #8c939d;
      width: 110px;
      height: 110px;
      line-height: 110px;
      &:hover {
        border-color: #409EFF;
      }
      .el-icon-plus {
        font-size: 28px;
        color: #8c939d;
        width: 100px;
        height: 100px;
        line-height: 100px;
        text-align: center;
      }
      .img {
        width: 100px;
        height: 100px;
        display: block;
      }
    }
    .el-upload-list__item{
      width: 110px;
      height: 110px;
      margin: 0 8px 0 0;
      vertical-align: middle;
    }
  }
  .el-carousel__container{
    height: 450px;
  }
</style>
